13. Handling Errors
Handling Errors Try Except Finally
Try Statement
We can use try
statements to handle exceptions. There are four clauses you can use (one more in addition to those shown in the video).
try
: This is the only mandatory clause in atry
statement. The code in this block is the first thing that Python runs in atry
statement.except
: If Python runs into an exception while running thetry
block, it will jump to theexcept
block that handles that exception.else
: If Python runs into no exceptions while running thetry
block, it will run the code in this block after running thetry
block.finally
: Before Python leaves thistry
statement, it will run the code in thisfinally
block under any conditions, even if it's ending the program. E.g., if Python ran into an error while running code in theexcept
orelse
block, thisfinally
block will still be executed before stopping the program.
Handling Error Specifying Exceptions
Specifying Exceptions
We can actually specify which error we want to handle in an except
block like this:
try:
# some code
except ValueError:
# some code
Now, it catches the ValueError exception, but not other exceptions. If we want this handler to address more than one type of exception, we can include a parenthesized tuple after the except
with the exceptions.
try:
# some code
except (ValueError, KeyboardInterrupt):
# some code
Or, if we want to execute different blocks of code depending on the exception, you can have multiple except
blocks.
try:
# some code
except ValueError:
# some code
except KeyboardInterrupt:
# some code